//
//  RestUploadFileView.swift
//  sui04mac
//
//  Created by 杨剑 on 2023/12/5.
//

import SwiftUI

struct RestUploadFileView: View {
    
    @Binding var filePath : String
    @State private var importing = false
    @Binding var fileData : Data?
    var body: some View {
        VStack {
            Spacer()
            Text(filePath)
            Button(action: {
//                importing = true
                
                let dialog = NSOpenPanel();
                dialog.title                   = "Choose a file";
                dialog.showsResizeIndicator    = true;
                dialog.showsHiddenFiles        = false;
                dialog.canChooseDirectories    = true;
                dialog.canCreateDirectories    = true;
                dialog.allowsMultipleSelection = false;

                if (dialog.runModal() == NSApplication.ModalResponse.OK) {
                    let result = dialog.url
                    if (result != nil) {
                        let path = result!.path
                        print(path)
                        filePath = path
                        let url = URL(fileURLWithPath: path)
                        fileData = FileManager.default.contents(atPath: url.path)
                        if fileData != nil {
                            print("选择文件成功")
                        }
                    }
                }
            }, label: {
                Text("选择文件")
                    .frame(width: 200,height: 50)
            })
            .fileImporter(
                isPresented: $importing,
                allowedContentTypes: [.text,.image,.audio,.video]
//                allowedContentTypes: [.plainText]
            ) { result in
                switch result {
                case .success(let file):
                    print(file.absoluteString)
                    filePath = file.absoluteString
                case .failure(let error):
                    print(error.localizedDescription)
                }
            }
            Spacer()
        }
    }
}

//#Preview {
////    RestUploadFileView(filePath: .constant(""))
//}
